package com.spider.im.chat;

import com.spider.im.chat.proto.ChatProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IMClientHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("链接服务端成功：" + ctx.channel().remoteAddress());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame frame) throws Exception {

        // 获取 ByteBuf 数据
        ByteBuf buffer = frame.content();
        // 将 ByteBuf 转换为 byte 数组
        byte[] bytes = new byte[buffer.readableBytes()];
        buffer.readBytes(bytes);
        // 解析 protobuf 消息
        ChatProto.MessageWrapper msg = ChatProto.MessageWrapper.parseFrom(bytes);
        log.info("Received Protobuf message: " + msg.getPayload());
        ChatProto.MessageType type = msg.getType();
        System.out.println("Server says: " + type);
    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        // 用户离线
        //onlineUsers.values().remove(ctx.channel());
        System.out.println("断开与服务端的链接：" + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
